﻿-- ==============================================
-- Filename:    GetSQL_SourceKeyPivot.sql
-- Function:    用于生成RuntimeView，源键转置部分的SQL语句
-- Author:      Patrick Pun
-- Modify Date: 2013-10-16
-- Commen:    
-- ==============================================

CREATE FUNCTION [Mapping].[GetSQL_SourceKeyPivot]
(
  @groupId int
)
RETURNS nvarchar(500)
AS
BEGIN
  DECLARE @str nvarchar(500)

  ;WITH KeyColumns AS (
    SELECT DISTINCT KeyColumn
      FROM Mapping.SourceKey
      WHERE MappingItem IN (SELECT Id FROM Mapping.MappingItem WHERE [Group] = @groupId) 
  )
  SELECT @str = IIF(@str IS NULL, '', @str + ', ') + 
      '[' + KeyColumn + ']'
    FROM KeyColumns

  RETURN @str
END
